package com.anytrek.websocket.springboot;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class MyWebSocketHandler extends AbstractWebSocketHandler {

    private static final Map<String, WebSocketSession> sessionMap;
    private static final StringBuffer stringBuffer;

    static {
        sessionMap = new ConcurrentHashMap<>();
        stringBuffer = new StringBuffer();
    }

    // 连接建立
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessionMap.put(session.getId(), session);
        stringBuffer.append(session.getId()).append("进入了群聊<br/>");
        log.debug("Client{} : 进入了群聊", session.getId());
        sendMessageToAll();
    }

    // 收到消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        stringBuffer.append(session.getId()).append(":").append(message.getPayload()).append("<br/>");
        log.debug("{} : {}", session.getId(), message.getPayload());
        sendMessageToAll();
    }

    // 传输异常
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        sessionMap.remove(session.getId());
    }

    // 连接关闭
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessionMap.remove(session.getId());
        stringBuffer.append(session.getId()).append("退出了群聊<br/>");
        log.debug("Client{} : 退出了群聊", session.getId());
        sendMessageToAll();
    }

    public void sendMessage(WebSocketSession session, String message) throws IOException {
        session.sendMessage(new TextMessage(message));
    }

    // 遍历所有存储在 sessionMap 中的 WebSocket 会话，并将 stringBuffer 的内容发送给每个客户端
    private void sendMessageToAll() throws IOException {
        for (WebSocketSession session : sessionMap.values()) {
            sendMessage(session, stringBuffer.toString());
        }
    }
}